package com.example.xgakj.newterminal.utils;


import com.example.xgakj.newterminal.beans.DeviceBean;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author Administrator
 * @date 2017-10-19
 */

public class NetUtil {
    /**
     * 转换查询参数
     * @param keys 参数KEY
     * @param values 值
     * @return json
     */
    public static String toJSON(String[] keys,String[] values)
    {
//		Gson g = new Gson();
        Gson g = new GsonBuilder().disableHtmlEscaping().create();
        LinkedHashMap<String, Object> map=new LinkedHashMap<String, Object>();
        if(keys.length==values.length)
        {
            for(int i=0;i<keys.length;i++)
            {
                if("fname".equals(keys[i]) || "fvalue".equals(keys[i]))
                {
                    String str = values[i];
                    String[] arrayStr = str.split(",");
                    List<String> list = java.util.Arrays.asList(arrayStr);
                    map.put(keys[i], list);
                }
                else
                {
                    map.put(keys[i], values[i]);
                }
            }
        }
        String json = g.toJson(map);
        return json;
    }

    /**
     * 解析设备列表
     * @param json 数据源
     * @return 返回设备列表
     */
    public static ArrayList<DeviceBean> parseDeviceList(String json)
    {
        Type type = new TypeToken<ArrayList<DeviceBean>>(){}.getType();
        Gson gson=new Gson();
        ArrayList<DeviceBean> list=gson.fromJson(json, type);
        return list;
    }

    public static String getUrl(String[] keys,String[] values)
    {
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<keys.length;i++)
        {
            sb.append(keys[i]);
            sb.append("=");
            sb.append(values[i]);
            if(i<keys.length-1)
            {
                sb.append("&");
            }
        }
        return sb.toString();
    }
}
